package SocketUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 接收socket流发送过来的文件流 使用方法：直接启动即可监控8821端口的情况
 */
public class FileIncepter {
	private int port = 8842;
	private ServerSocket ss = null;
	private String filePath = "";

	public FileIncepter() {

	}

	/**
	 * @描述：接收socket发送过来的文件
	 * 
	 * @时间：上午9:10:58
	 * @开发者：稀饭 @测试：通过
	 */
	private void acceptFile(Socket socket) throws IOException {

		DataOutputStream dos = null;
		DataInputStream dis = null;
		try {
			dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		// 接收文件的文件名
		String fileName = dis.readUTF() + "";
		File file = new File(filePath + fileName);
		dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
		System.out.println("文件的名字" + fileName);
		System.out.println("开始接收文件!");
		try {
			byte[] b = new byte[1024];
			int i = 0;
			while ((i = dis.read(b)) != -1) {
				dos.write(b, 0, i);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		} finally {
			// 关闭所有连接
			try {
				if (dos != null)
					dos.close();
			} catch (IOException e) {
			}
			try {
				if (dis != null)
					dis.close();
			} catch (IOException e) {
			}
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * @描述：创建socket对象
	 * 
	 * @时间：下午2:33:51
	 * @开发者：稀饭 @测试：通过
	 * @param
	 */
	private void createSocket() {
		try {
			ss = new ServerSocket(port);
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		while (true) {
			try {
				final Socket socket = ss.accept();
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							acceptFile(socket);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		new FileIncepter().createSocket();
	}
}
